
local uci  = require "luci.model.uci".cursor()

function filter_set(enable, rule)
	local code=0
	
	uci:set("filter", "list", "enable", enable)
	uci:set("filter", "list", "rule", rule)
	
	-- 轮询删除防火墙数据
	uci:foreach("firewall", "rule", function(s)							
		local lcName = s[".name"]
		local name = uci:get("firewall", lcName, "name")

		if name and name == "FilterRule" then
			uci:delete("firewall", lcName)
		end
	end)
	
	if enable == "1" then
		uci:foreach("filter", rule, function(s)							
				local lcName = s[".name"]
				local macaddr = uci:get("filter", lcName, "mac")					-- MAC地址
				local name = uci:get("filter", lcName, "name")						-- 描述

				local lcName = uci:add("firewall", "rule")
				uci:set("firewall", lcName, "src", "lan")
				uci:set("firewall", lcName, "dest", "wan")
				uci:set("firewall", lcName, "proto", "tcpudp")
				uci:set("firewall", lcName, "name", "FilterRule")
				uci:set("firewall", lcName, "src_mac", macaddr)
				
				if rule == "allow" then
					uci:set("firewall", lcName, "target", "ACCEPT")
				else
					uci:set("firewall", lcName, "target", "REJECT")
				end
		end)
		
		if rule == "allow" then
			local lcName = uci:add("firewall", "rule")
			uci:set("firewall", lcName, "src", "lan")
			uci:set("firewall", lcName, "dest", "wan")
			uci:set("firewall", lcName, "target", "REJECT")
			uci:set("firewall", lcName, "name", "FilterRule")
		end
	end
	
	if code == 0 then
		uci:commit("filter")
		uci:commit("firewall")
		os.execute("/etc/init.d/firewall restart")
	end
	
	return code
end

local enable = arg[1]
local rule = arg[2]
if not enable or not rule then
	return
end

filter_set(enable, rule)